package com.ysm.smfu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ysm.smfu.activity.All_LoginActivity;
import com.ysm.smfu.activity.BaseActivity;
import com.ysm.smfu.bean.VersionInfo;
import com.ysm.smfu.chat.ZHChatFragment;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.fragment.FragmentFactory;
import com.ysm.smfu.fragment.MyBaseFragment;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.MyImageBitmapUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.AdActivity;
import com.ysm.smfu.welcome.SharedConfig;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.iflytek.autoupdate.IFlytekUpdate;
import com.iflytek.autoupdate.IFlytekUpdateListener;
import com.iflytek.autoupdate.UpdateConstants;
import com.iflytek.autoupdate.UpdateErrorCode;
import com.iflytek.autoupdate.UpdateInfo;
import com.iflytek.autoupdate.UpdateType;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import chatuidemo.Constant;
import chatuidemo.DemoHelper;
import okhttp3.Call;

public class MainActivity extends BaseActivity {

    private static final String TAG = "DeMeiHui";
    @BindView(R.id.pager)
    ViewPager pager;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_chat)
    RadioButton rbChat;
    @BindView(R.id.rb_found)
    RadioButton rbFound;
    @BindView(R.id.rb_my)
    RadioButton rbMy;
    @BindView(R.id.rg_home)
    RadioGroup rgHome;
    @BindView(R.id.unread)
    TextView unread;

    private android.app.AlertDialog.Builder conflictBuilder;
    private String name;
    private SharedPreferences sp;
    private IFlytekUpdate iFlytekUpdate;
    private int posi;
    private MyReceiver myreceiver;
    private MyBaseFragment fragment;
    private String preAdImg;
    private String currAdImg;
    private String preLink;
    private String currLink;
    private String currAdId;
    private String isVip;
    private int versionCode;

    String config;
    private String appVersionCode;

    @Override
    protected void init() {
        super.init();
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                getConfig();
                killWecPage();
                if (dealConfict()) return;
                saveAdInfo();
                getVersionCode();
                updateVersion();
                getUpdataConfig();
                goTestVersion();
            }
        });
        getType();
    }

    /**
     * 处理登录冲突问题
     *
     * @return
     */
    private boolean dealConfict() {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            finish();
            startActivity(new Intent(this, All_LoginActivity.class));
            return true;
        }
        return false;
    }

    private void getConfig() {
        isVip = getIntent().getStringExtra("isVip");
        if (TextUtils.equals(isVip, "isVip"))
            setCurrItemToMy();
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        preAdImg = sp.getString(SpKey.PREADIMG, "");
        preLink = sp.getString(SpKey.PREADLINK, "");
        currAdImg = sp.getString(SpKey.CURRADIMG, "");
        currLink = sp.getString(SpKey.CURRLINK, "");
        currAdId = sp.getString(SpKey.CURRPREADID, "");
        name = sp.getString(SpKey.NAME, "");
        //进入主页面之后，不在显示引导页
        sp.edit().putBoolean("first", false).commit();
    }

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setNoSuitStatuBar();
        registerForChat();
        //设置adpater
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
//        同时加载4张fragment
        pager.setOffscreenPageLimit(4);
        rgHome.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int item_id = rgHome.indexOfChild(rgHome.findViewById(checkedId));
                pager.setCurrentItem(item_id, false);
            }
        });
        rgHome.check(R.id.rb_home);
//        默认显示
        // 请求服务器数据
        // 监听ViewPager切换 重新请求服务器数据
        pager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                fragment = FragmentFactory.create(position);
                posi = position;
                rgHome.check(rgHome.getChildAt(position).getId());
                fragment.refresh();
            }

            /**
             * 预览下张页面
             * @param position
             * @param positionOffset
             * @param positionOffsetPixels
             */
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    int id = rgHome.getChildAt(posi).getId();
                    rgHome.check(id);
                }
            }
        });
        boolean isShowAdPage = getIntent().getBooleanExtra("isShowAdPage", false);
        if (isShowAdPage)
            UIUtils.startActivity(AdActivity.class);
    }

    /**
     * 缓存广告图片
     */
    private void saveAdInfo() {
        if (!TextUtils.isEmpty(currAdImg) && !TextUtils.equals(currAdImg, preAdImg)) {
            // 更新上次广告信息为当前信息
            sp.edit().putString(SpKey.PREADIMG, currAdImg).commit();
            sp.edit().putString(SpKey.PREADLINK, currLink).commit();
            sp.edit().putString(SpKey.PREADID, currAdId).commit();
            getBitmapAndSaveToLocal(currAdImg);
        } else {
            Bitmap locAdBitmap = MyImageBitmapUtil.getBitmapLoc(SpKey.LOCALADIMGADD);
            if (locAdBitmap == null)
                getBitmapAndSaveToLocal(preAdImg);
        }
        // 清空当前保存广告信息
        sp.edit().putString(SpKey.CURRADIMG, "").commit();
        sp.edit().putString(SpKey.CURRLINK, "").commit();
        sp.edit().putString(SpKey.CURRPREADID, "").commit();
    }

    /**
     * 获取广告图片并缓存到本地
     *
     * @param adImg
     */
    private void getBitmapAndSaveToLocal(String adImg) {
        if (TextUtils.isEmpty(adImg))
            return;
        OkHttpUtils.get().url(adImg)
                .build().execute(new BitmapCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                PrintUtil.printRespones("保存广告图片失败", e.getMessage());
            }

            @Override
            public void onResponse(Bitmap response, int id) {
//                将广告图片保存到本地
                MyImageBitmapUtil.saveBitmapLoc(response, SpKey.LOCALADIMGADD);
            }
        });
    }

    /**
     * 检测新版本
     */
    private void goTestVersion() {
        BaseProtocal.builder(false).checkVersion(new MyStringCallBack() {

            @Override
            public void onSuccess(String response) {
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    VersionInfo versionInfo = new Gson().fromJson(response, VersionInfo.class);
                    List<VersionInfo.HistoryVersionInfo> historyVersionInfos = versionInfo.versionInfo;
                    appVersionCode = historyVersionInfos.get(0).appVersionCode;
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast("网络繁忙，请稍后重试");
            }
        }, 1, 1);
    }

    private void registerForChat() {
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction("tochatM");
        myreceiver = new MyReceiver();
        registerReceiver(myreceiver, intentfilter);
    }

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            pager.setCurrentItem(1, false);
        }
    }

    @Override
    protected void beforeOnResumeInitMobclickAgent() {
    }

    @Override
    protected void beforeOnPauseInitMobclickAgent() {
    }

    @Override
    protected void afterResume() {
        super.afterResume();
//        //    更新未读消息数
        updateUnreadLabel();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);

        if (isHasShowUpdatePage && TextUtils.equals(config, "00")) {
            int parseVersionCode;
            try {
                parseVersionCode = Integer.parseInt(appVersionCode);
            } catch (Exception e) {
                parseVersionCode = 1;
            }
            if (parseVersionCode > versionCode)//强制更新
                killAll();
        }
    }

    @Override
    protected void onStop() {
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        super.onStop();
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                updateUnreadLabel();
            }
        });
    }

    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            unread.setText(String.valueOf(count));
            unread.setVisibility(View.VISIBLE);
        } else {
            unread.setVisibility(View.INVISIBLE);
        }
        if (pager.getCurrentItem() == 1) {
            if (fragment instanceof ZHChatFragment) {
                ((ZHChatFragment) fragment).refreshConversation();
            }
        }
    }

    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    /**
     * 讯飞版本更新
     */
    public void updateVersion() {
        iFlytekUpdate = IFlytekUpdate.getInstance(this);
//        iFlytekUpdate.setDebugMode(true);
        iFlytekUpdate.setParameter(UpdateConstants.EXTRA_WIFIONLY, "true");
        iFlytekUpdate.setParameter(UpdateConstants.EXTRA_STYLE, UpdateConstants.UPDATE_UI_DIALOG);
        iFlytekUpdate.autoUpdate(MainActivity.this, updateListener);
    }

    private void getUpdataConfig() {
        BaseProtocal.builder(false).getUpdataConfig(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("是否强推:" + response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String config = jsonObject.optString("state");
                        MainActivity.this.config = config;
//                        if (TextUtils.equals(config, "01")) {
//                            //        强制更新
//                            iFlytekUpdate.forceUpdate(MainActivity.this, new IFlytekUpdateListener() {//无效
//                                @Override
//                                public void onResult(int i, UpdateInfo updateInfo) {
//                                }
//                            });
//                        } else
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
            }
        }, String.valueOf(versionCode));
    }

    //    是否已经显示更新页面
    boolean isHasShowUpdatePage;
    private IFlytekUpdateListener updateListener = new IFlytekUpdateListener() {

        @Override
        public void onResult(final int errorcode, UpdateInfo result) {

            if (errorcode == UpdateErrorCode.OK && result != null) {
                if (result.getUpdateType() == UpdateType.NoNeed) {
//                    showTip("已经是最新版本！");
                    return;
                }
                iFlytekUpdate.showUpdateInfo(MainActivity.this, result);
                isHasShowUpdatePage = true;
            }
        }
    };

    /**
     * ViewPager显示的Fragment
     */
    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            MyBaseFragment fragment = FragmentFactory.create(position);
            return fragment;
        }

        @Override
        public int getCount() {
//            return 3;
            return rgHome.getChildCount();
        }
    }

    /**
     * 是否已经点击过一次
     */
    boolean isPressedOnce;
    private long secondTime;
    private long firstTime;


    @Override
    public void onBackPressed() {
        againQuit();
    }

    /**
     * 再点一次退出
     */
    private void againQuit() {
        if (isPressedOnce) {
            // 说明刚才已经点了一次 这是第二次进入
            // 先拿到第二次点的时间
            secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                // 说明上一次点击作废了
                isPressedOnce = true;
                // 0时间2秒  1 4秒
                ToastUtils.showToast("再点一次退出");
                firstTime = System.currentTimeMillis();
            } else {
                killAll();
                ToastUtils.cancelToast();
                // 界面结束之后让这些状态保持刚开始的样子
                isPressedOnce = false;
                firstTime = 0;
                secondTime = 0;
            }
        } else {
            // 说明是第一次进入
            isPressedOnce = true;
            // 0时间2秒  1 4秒
            ToastUtils.showToast("再点一次退出");
            firstTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
        unregisterReceiver(myreceiver);
    }

    /**
     * 获取商家分类
     * /business/bClassList
     */
    private void getType() {
        BaseProtocal.builder(true).getType(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("商家分类信息", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    sp.edit().putString(SpKey.CATEGORY, response).commit();
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    /**
     * 切换到聊天界面
     */
    public void setCurrItem() {
        if (pager != null)
            pager.setCurrentItem(1);
    }

    /**
     * 切换到个人中心
     */
    public void setCurrItemToMy() {
        if (pager != null)
            pager.setCurrentItem(3);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        dealConfict(intent);
    }

    /**
     * 处理登录冲突问题
     *
     * @return
     */
    private boolean dealConfict(Intent intent) {
        if (intent != null && intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)) {
//            finish();
            Intent intent2 = new Intent(this, All_LoginActivity.class);
            intent2.putExtra(Constant.ACCOUNT_CONFLICT, true);
            startActivity(intent2);
            return true;
        }
        return false;
    }

    /**
     * 获取版本号和版本名
     */
    private void getVersionCode() {
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
}
